const Busboy = require('busboy');
const fs = require('fs');
const path = require('path');

// 上传文件存储的路径，用于文件迁移的时候进行修改
const staticPath = path.join(path.dirname(__dirname), 'static');

function _getSuffixName(fileName) {
  if (!fileName) {
    return "";
  }
  let nameList = fileName.split('.');
  if (nameList.length == 0) {
    return "";
  }
  let type = nameList[nameList.length - 1];
  return type;
}

async function _uploadFile(ctx, next) {
  if (ctx.method != 'POST') {
    next && await next();
    return;
  }
  if (path.dirname(ctx.url) === '/api/upload') {
  let lastPath =  path.basename(ctx.url); // img或者file
  let date = new Date();
  let filePath = path.join(staticPath, lastPath, `${date.getFullYear()}-${date.getMonth()}-${date.getDay()}`);
  let filePromise = fs.promises;  // node 10.0之后的api
  if (!fs.existsSync(filePath)) {
    await filePromise.mkdir(filePath);
  }
  let result = await _writeStream(ctx, filePath, lastPath);
  ctx.body = result;    // 响应数据
  } else {
    next && await next();
  }
}

function _writeStream(ctx, filePath, typePath) {
  let busboy = new Busboy({headers: ctx.headers});
  let result = []; // 写入文件后的url路径,用koa-static 可以访问的路径
  let extraPars = {}; // 额外的数据
  return new Promise((resolve, reject)=>{
    ctx.req.pipe(busboy);
    busboy.on('file', (fieldname, stream, filename, encoding, mimetype)=>{
      let randomFileName = Math.random().toString(6).substr(2) + '.' + _getSuffixName(filename); // 生成一个随机的文件名字。
      let uploadFilePath = path.join(filePath, randomFileName);
      stream.pipe(fs.createWriteStream(uploadFilePath));
      stream.on('end', ()=>{
        let fileURL = `http://${ctx.host}/${typePath}/${path.basename(filePath)}/${randomFileName}`;
        result.push(fileURL);
        console.log('写入文件成功');
      });
    });
    // 处理非文件的文本数据
    busboy.on('field', (fieldname, val, fieldnameTruncated, valTruncated, encoding, mimetype)=>{
      console.log(`表单数据是:${fieldname}->${val}`);
      extraPars[fieldname] = val;
    });
    busboy.on('finish', ()=>{
      console.log("文件上传结束");
      resolve({urls: result, pars: extraPars});
    });
    busboy.on('error', (err)=>{
      reject(err);
      console.log('文件上传失败');
    });
  });
}
module.exports = {uploadFile: ()=>{
  return _uploadFile;
}};
